package com.example.partner.fragment;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.partner.R;
import com.example.partner.activity.ChatActivity;
import com.example.partner.common.BaseResponse;
import com.example.partner.common.UserInfoViewModel;
import com.example.partner.model.domain.User;
import com.example.partner.service.UserService;
import com.google.android.flexbox.FlexboxLayout;

import org.json.JSONArray;
import org.json.JSONException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserInfoFragment extends Fragment {
    private UserService userService;
    TextView profileTextView,phoneTextView,roleTextView;
    FlexboxLayout tagsContainer;
    String userAccount;
    private UserInfoViewModel viewModel;
    Button btsend;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        return inflater.inflate(R.layout.fragment_user_info, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 获取与 Fragment 关联的 Activity 的 SharedPreferences
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
        Long userId = sharedPreferences.getLong("userId", -1);
        // 在这里初始化 UI 组件
        profileTextView = view.findViewById(R.id.profile);
        phoneTextView = view.findViewById(R.id.phone);
        roleTextView = view.findViewById(R.id.role);
        tagsContainer = view.findViewById(R.id.tags);
        btsend=view.findViewById(R.id.btSendmessage);
        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 替换为您的服务器地址
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        userService = retrofit.create(UserService.class);
        viewModel = new ViewModelProvider(requireActivity()).get(UserInfoViewModel.class);
        userAccount = viewModel.getUserAccount();
        MatchUsers(userAccount);
        btsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(getContext(), ChatActivity.class);
                intent.putExtra("toid",viewModel.getUserId());
                intent.putExtra("username", viewModel.getUsername());
                intent.putExtra("avatar",viewModel.getAvatarUrl());
                startActivity(intent);
            }
        });
    }


    private void MatchUsers(String userAccount) {
        userService.findByAccount(userAccount).enqueue(new Callback<BaseResponse<User>>() {
            @Override
            public void onResponse(Call<BaseResponse<User>> call, Response<BaseResponse<User>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    User user = response.body().getData();
                    if (user == null){
                        Toast.makeText(getContext(), "不存在该用户", Toast.LENGTH_SHORT).show();
                    }else {
                        profileTextView.setText(user.getProfile());
                        phoneTextView.setText(user.getPhone());
                        if (user.getUserRole() == 0){
                            roleTextView.setText("普通用户");
                        }else
                            roleTextView.setText("管理员");
                        String jsonString = user.getTags();
                        if(jsonString!=null) {
                            try {
                                // 将JSON字符串转换为JSONArray
                                JSONArray jsonArray = new JSONArray(jsonString);

                                // 创建一个字符串数组来存储解析后的数据
                                String[] tagsArray = new String[jsonArray.length()];

                                // 遍历JSONArray，将每个元素添加到字符串数组中
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    tagsArray[i] = jsonArray.getString(i);
                                }
                                // 输出解析后的字符串数组
                                for (String tag : tagsArray) {
                                    // 创建一个新的ContextThemeWrapper，传入当前的Context和您的样式资源
                                    ContextThemeWrapper newContext = new ContextThemeWrapper(getContext(), R.style.TagStyle);

                                    // 使用新的Context来创建一个TextView
                                    TextView tagView = new TextView(newContext);
                                    tagView.setText(tag);
                                    // 设置TextView的其他属性，如margin，padding等
                                    FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                                            ViewGroup.LayoutParams.WRAP_CONTENT,
                                            ViewGroup.LayoutParams.WRAP_CONTENT);
                                    layoutParams.setMargins(10, 5, 10, 5); // 根据需要设置margin值
                                    tagView.setLayoutParams(layoutParams);

                                    // 最后，将TextView添加到FlexboxLayout中
                                    tagsContainer.addView(tagView);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }



                    }
                } else {
                    // 处理错误情况

                }
            }

            @Override
            public void onFailure(Call<BaseResponse<User>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }





}
